package hotel.controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import hotel.dao.HotelDao;
import hotel.modal.Customer;
import hotel.modal.Room;
import hotel.modal.RoomRent;
import hotel.modal.RoomReserve;
import hotel.modal.RoomType;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.control.Label;

import javafx.scene.control.ScrollPane;
import javafx.scene.layout.TilePane;

import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;

public class MainCenterPageController {
	@FXML
	private Label commentLb;
	@FXML
	private Label roomNoLb;
	@FXML
	private Label roomStatusLb;
	@FXML
	private Label roomTypeLb;
	@FXML
	private Label positionLb;
	@FXML
	private Label customerNameLb;
	@FXML
	private Label customerPhoneLb;
	@FXML
	private Label startTimeLb;
	@FXML
	private Label LeaveTimeLb;
	@FXML
	private Label avaliableRoomLb;
	@FXML
	private Label rerserveRoomLb;
	@FXML
	private Label rentRoomLb;
	@FXML
	private Label dirtyRoomLb;
	@FXML
	private VBox vbox;
	@FXML
	private ChoiceBox<String> typeCh;
	@FXML
	private ChoiceBox<String> statusCh;
	@FXML
	private ChoiceBox<String> positionCh;
	@FXML
	private TextField searchField;
	@FXML
	private ScrollPane scrollPane;
	@FXML
	private TilePane tilePane;
	
	private List<RoomType> roomTypeList = null;
	private ObservableList<String> typeNameList;
	private ObservableList<String> positionList;
	
	@FXML
	public void initialize() {
		
		// 初始化数据
		initComponent();
		
		// 加载数据
		loadData();
	}
	
	private void initComponent() {
		String choice = null;
		roomTypeList = HotelDao.getAllRoomType();
		typeNameList = typeCh.getItems();
		for(RoomType t:roomTypeList) {
			choice  = t.getTypeName();
			if(t.isHourRoom()) choice += "(钟点房)";
			typeNameList.add(choice);
		}

		positionList = positionCh.getItems();
		positionList.addAll(HotelDao.getAllRoomPosition());
		//positionCh.setItems(positionList);
		
		typeCh.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) {
				chChanged(1, newVal);
			}
		});
		
		statusCh.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) {
				chChanged(2, newVal);
			}
		});
		
		positionCh.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) {
				chChanged(3, newVal);
			}
		});
	}

	private void loadData() {
		refresh();
	}
	
	public void refresh() {
		displayData(HotelDao.getAllRoom());
		// 统计各个状态的房间
		int avaliable = HotelDao.countRoomStatus(1);
		int reserve = HotelDao.countRoomStatus(2);
		int rent = HotelDao.countRoomStatus(3);
		int dirty = HotelDao.countRoomStatus(4);
		avaliableRoomLb.setText(String.valueOf(avaliable));
		rerserveRoomLb.setText(String.valueOf(reserve));
		dirtyRoomLb.setText(String.valueOf(dirty));
		rentRoomLb.setText(String.valueOf(rent));
		
	}
	
	private void displayData(List<Room> rooms) {
		Button button = null;
		String roomType = null;
		if(rooms == null || rooms.size() <= 0) return;
		
		tilePane.getChildren().clear();
		Color c= null;
		for(Room t:rooms) {
			roomType = t.getTypeName();
			if(t.isHourRoom()) { roomType += "(钟点房)"; }
			button = this.getNewButton(t, roomType);	
			switch (t.getStatus()) {
			case 1: c= Color.web("#5AB770"); break;
			case 2: c= Color.web("#569CE3"); break;
			case 3: c= Color.web("#E064B7"); break;
			case 4: c= Color.web("#FF981D"); break;
			case 5: c= Color.web("#FF0000"); break;
			default: c= Color.web("#33CC33"); break;
			}
			String rc = String.format("rgba(%f, %f, %f, 0.9);", c.getRed()*255, c.getGreen()*255, c.getBlue()*255);
			//if(i == 0) System.out.println(rc);
			button.setStyle("-fx-background-color: "+rc);
			tilePane.getChildren().add(button);
		}
	}
	
	private void chChanged(int type, String newVal) {
		String col = null;
		
		if(type == 1) { 
			col = "房间类型"; 
			int index = typeCh.getSelectionModel().getSelectedIndex();
			if(index < 1) {
				newVal = "";
			}else{
				RoomType roomType = roomTypeList.get(index - 1);
				newVal = String.valueOf(roomType.getTypeId());
			}
		}else if(type == 2) { 
			newVal = statusCh.getSelectionModel().getSelectedItem();
			col = "房间状态"; 
		}
		else if(type == 3) { 
			col = "房间位置";
		}
		if(newVal.equals("全部")) newVal = "";
		List<Room> roomList = HotelDao.getRoomCondSearch(col, newVal);
		displayData(roomList);
	}
	
	public void setInitData() {
		
	}
	
	
	private Button getNewButton(Room room, String roomType) {
		try {
			FXMLLoader tfxmlLoader = new FXMLLoader(getClass().getResource("/hotel/view/RoomButton.fxml"));
			Button button = (Button)tfxmlLoader.load();
			button.setUserData(room);
			RoomButtonController controller = tfxmlLoader.<RoomButtonController>getController();
			controller.setRoom(room);
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			button.setOnMouseClicked(new EventHandler<MouseEvent>() {
				@Override
				public void handle(MouseEvent event) {
					MouseButton mbutton = event.getButton();
					if(mbutton == MouseButton.PRIMARY) {
						Room room = (Room)button.getUserData();
						roomNoLb.setText(room.getRoomNo());
						roomStatusLb.setText(getRoomStatus(room.getStatus()));
						String roomType = room.getTypeName();
						if(room.isHourRoom()) { roomType += "(钟点房)"; }
						roomTypeLb.setText(roomType);
						positionLb.setText(room.getPosition());
						tilePane.setUserData(room);
						customerNameLb.setText("");
						customerPhoneLb.setText("");
						commentLb.setText("");
						startTimeLb.setText("");
						LeaveTimeLb.setText("");
						if(room.getStatus() == 3) {
							RoomRent roomRent = HotelDao.getRoomRentFromRoom(room.getRoomNo());
							if(roomRent == null || roomRent.getPreOrderId().equals("")) return; 
							startTimeLb.setText(roomRent.getStartTime());
							LocalDateTime ldt = LocalDateTime.parse(roomRent.getStartTime(), formatter);
							if(room.isHourRoom()) {
								ldt = ldt.plusHours(roomRent.getDuration());		
							}else {
								ldt = ldt.plusDays(roomRent.getDuration());
							}
							LeaveTimeLb.setText(ldt.format(formatter));
							commentLb.setText(roomRent.getComment());
							if(roomRent.getCustomerNo() == 0) return;
							Customer customer = HotelDao.getCustomer(roomRent.getCustomerNo());
							if(customer == null) return;
							customerNameLb.setText(customer.getName());
							customerPhoneLb.setText(customer.getPhone());
						}else if(room.getStatus() == 2) {
							RoomReserve rr = HotelDao.getRoomReserveFromRoom(room.getRoomNo());
							if(rr == null) return;
							customerNameLb.setText(rr.getName());
							customerPhoneLb.setText(rr.getPhone());
							commentLb.setText(rr.getComment());
							startTimeLb.setText(rr.getPresetTime());
							LeaveTimeLb.setText("");
						}					
						if(event.getClickCount() == 2) {
							//System.out.println("双击");
						}
					}
				}
				
			});
			return button;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void onSearchFieldAction(ActionEvent event) {
		String newVal = "";
		newVal = searchField.getText();
		List<Room> roomList = HotelDao.getRoomCondSearch("", newVal);
		displayData(roomList);
	}
	
	public static String getRoomStatus(int status) {
		String str = null;
		switch (status) {
		case 1:
			str = "可供"; break;
		case 2:
			str = "预定"; break;
		case 3:
			str = "入住"; break;
		case 4:
			str = "脏房"; break;
		case 5:
			str = "停用"; break;
		default: str = "未知"; break;
		}
		return str;
	} 

}
